import hashlib
import random
import requests
import polib
import time
from urllib.parse import quote
import configparser

config = configparser.ConfigParser()
config.read('settings.ini')

en_file = config.get('Paths', 'en_file')
ru_file = config.get('Paths', 'ru_file')
zh_file = config.get('Paths', 'zh_file')
search_path = config.get('Paths','search_path')


appid = '20220616001249928'
secretKey = 'y4gECHNYkCcJ9rOCexGk'
api_url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'

def get_translation(query):
    salt = random.randint(32768, 65536)
    sign = appid + query + str(salt) + secretKey
    md5 = hashlib.md5(sign.encode()).hexdigest()
    url = api_url + '?appid=' + appid + '&q=' + quote(query) + '&from=' + from_lang + '&to=' + to_lang + '&salt=' + str(salt) + '&sign=' + md5
    response = requests.get(url)
    result = response.json()
    print(result['trans_result'][0]['dst'])
    time.sleep(0.1)
    return result['trans_result'][0]['dst']

def process_po_file(file_path):
    po = polib.pofile(file_path)
    hasSave = False
    for entry in po:
        if not entry.msgstr:  # Only translate if msgstr is empty
            hasSave = True
            entry.msgstr = get_translation(entry.msgid)
    if hasSave:
        po.save(file_path)


from_lang = 'zh'
to_lang = 'en'
process_po_file(en_file)

from_lang = 'zh'
to_lang = 'ru'
process_po_file(ru_file)